import { createApp } from 'vue'
import { faker } from '@faker-js/faker/locale/zh_CN'

const app = {
    data() {
        return {
            // 表结构配置
            tableConfig: {
                tableName: '',
                columns: []
            },
            // 生成配置
            generateConfig: {
                count: 10
            },
            // 数据类型选项
            dataTypeOptions: [
                { label: '姓名', value: 'name' },
                { label: '手机号', value: 'phone' },
                { label: '邮箱', value: 'email' },
                { label: '日期时间', value: 'datetime' },
                { label: '整数', value: 'number' },
                { label: '文本', value: 'text' },
                { label: '地址', value: 'address' },
                { label: '公司名', value: 'company' },
                { label: 'IP地址', value: 'ip' },
                { label: 'URL', value: 'url' }
            ],
            // 生成的SQL语句
            generatedSQL: '',
            createTableSQL: '',
            activeTab: 'manual',
            
            // 新增：SQL类型到faker类型的映射
            sqlTypeMap: {
                'varchar': 'text',
                'char': 'text',
                'text': 'text',
                'int': 'number',
                'bigint': 'number',
                'datetime': 'datetime',
                'timestamp': 'datetime',
                'date': 'datetime'
            }
        }
    },
    methods: {
        // 添加新列
        addColumn() {
            this.tableConfig.columns.push({
                name: '',
                type: '',
                dataType: ''
            })
        },
        
        // 删除列
        removeColumn(index) {
            this.tableConfig.columns.splice(index, 1)
        },

        // 生成测试数据
        generateData() {
            const inserts = []
            for (let i = 0; i < this.generateConfig.count; i++) {
                const values = this.tableConfig.columns.map(column => {
                    return this.generateValue(column.dataType)
                })
                
                const sql = `INSERT INTO ${this.tableConfig.tableName} (${
                    this.tableConfig.columns.map(c => c.name).join(', ')
                }) VALUES (${values.join(', ')});`
                
                inserts.push(sql)
            }
            this.generatedSQL = inserts.join('\n')
        },

        // 根据数据类型生成值
        generateValue(type) {
            switch (type) {
                case 'name':
                    return `'${faker.person.fullName()}'`
                case 'phone':
                    return `'${faker.phone.number()}'`
                case 'email':
                    return `'${faker.internet.email()}'`
                case 'datetime':
                    return `'${faker.date.recent().toISOString()}'`
                case 'number':
                    return faker.number.int({ min: 1, max: 1000 })
                case 'text':
                    return `'${faker.lorem.sentence()}'`
                case 'address':
                    return `'${faker.location.streetAddress()}'`
                case 'company':
                    return `'${faker.company.name()}'`
                case 'ip':
                    return `'${faker.internet.ip()}'`
                case 'url':
                    return `'${faker.internet.url()}'`
                default:
                    return 'NULL'
            }
        },

        // 新增：解析CREATE TABLE语句
        parseCreateTable() {
            try {
                // 提取表名
                const tableNameMatch = this.createTableSQL.match(/CREATE\s+TABLE\s+[`]?(\w+)[`]?\s*\(/i)
                if (tableNameMatch) {
                    this.tableConfig.tableName = tableNameMatch[1]
                }

                // 提取列定义
                const columnsStr = this.createTableSQL.match(/\(([\s\S]*)\)/i)[1]
                const columnDefs = columnsStr.split(',')
                    .map(col => col.trim())
                    .filter(col => col && !col.toLowerCase().startsWith('primary') && !col.toLowerCase().startsWith('key'))

                // 解析每一列
                this.tableConfig.columns = columnDefs.map(colDef => {
                    const parts = colDef.trim().split(/\s+/)
                    const name = parts[0].replace(/[`'"]/g, '')
                    const sqlType = parts[1].toLowerCase().replace(/[\(\d\)]/g, '')
                    
                    return {
                        name,
                        type: parts[1],
                        dataType: this.mapSqlTypeToFaker(sqlType)
                    }
                })

                this.$message.success('解析成功')
            } catch (error) {
                this.$message.error('CREATE TABLE语句解析失败，请检查格式是否正确')
                console.error(error)
            }
        },

        // 新增：SQL类型映射到faker类型
        mapSqlTypeToFaker(sqlType) {
            return this.sqlTypeMap[sqlType] || 'text'
        }
    },
    template: `
        <el-container style="padding: 20px;">
            <el-main>
                <h2>SQL测试数据生成器</h2>
                
                <!-- 添加Tab切换 -->
                <el-tabs v-model="activeTab">
                    <el-tab-pane label="手动配置" name="manual">
                        <!-- 原有的手动配置表单 -->
                        <el-form label-width="100px">
                            <el-form-item label="表名">
                                <el-input v-model="tableConfig.tableName" placeholder="请输入表名"></el-input>
                            </el-form-item>
                            
                            <!-- 列配置 -->
                            <el-form-item label="表结构">
                                <el-button type="primary" @click="addColumn">添加列</el-button>
                                
                                <div v-for="(column, index) in tableConfig.columns" :key="index" style="margin-top: 10px;">
                                    <el-row :gutter="10">
                                        <el-col :span="6">
                                            <el-input v-model="column.name" placeholder="列名"></el-input>
                                        </el-col>
                                        <el-col :span="6">
                                            <el-input v-model="column.type" placeholder="SQL类型"></el-input>
                                        </el-col>
                                        <el-col :span="6">
                                            <el-select v-model="column.dataType" placeholder="数据类型">
                                                <el-option
                                                    v-for="option in dataTypeOptions"
                                                    :key="option.value"
                                                    :label="option.label"
                                                    :value="option.value">
                                                </el-option>
                                            </el-select>
                                        </el-col>
                                        <el-col :span="4">
                                            <el-button type="danger" @click="removeColumn(index)">删除</el-button>
                                        </el-col>
                                    </el-row>
                                </div>
                            </el-form-item>
                            
                            <!-- 生成配置 -->
                            <el-form-item label="生成数量">
                                <el-input-number v-model="generateConfig.count" :min="1" :max="1000"></el-input-number>
                            </el-form-item>
                            
                            <el-form-item>
                                <el-button type="primary" @click="generateData">生成SQL</el-button>
                            </el-form-item>
                        </el-form>
                    </el-tab-pane>
                    
                    <el-tab-pane label="解析建表语句" name="parse">
                        <el-form label-width="100px">
                            <el-form-item label="CREATE TABLE">
                                <el-input
                                    v-model="createTableSQL"
                                    type="textarea"
                                    :rows="5"
                                    placeholder="请输入CREATE TABLE语句"
                                ></el-input>
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" @click="parseCreateTable">解析</el-button>
                            </el-form-item>
                        </el-form>
                    </el-tab-pane>
                </el-tabs>
                
                <!-- 表结构展示（两种模式共用） -->
                <el-form label-width="100px" v-if="tableConfig.columns.length > 0">
                    <el-form-item label="表名">
                        <el-input v-model="tableConfig.tableName" placeholder="请输入表名"></el-input>
                    </el-form-item>
                    
                    <el-form-item label="表结构">
                        <div v-for="(column, index) in tableConfig.columns" :key="index" style="margin-top: 10px;">
                            <el-row :gutter="10">
                                <el-col :span="6">
                                    <el-input v-model="column.name" placeholder="列名"></el-input>
                                </el-col>
                                <el-col :span="6">
                                    <el-input v-model="column.type" placeholder="SQL类型"></el-input>
                                </el-col>
                                <el-col :span="6">
                                    <el-select v-model="column.dataType" placeholder="数据类型">
                                        <el-option
                                            v-for="option in dataTypeOptions"
                                            :key="option.value"
                                            :label="option.label"
                                            :value="option.value">
                                        </el-option>
                                    </el-select>
                                </el-col>
                                <el-col :span="4">
                                    <el-button type="danger" @click="removeColumn(index)">删除</el-button>
                                </el-col>
                            </el-row>
                        </div>
                    </el-form-item>
                    
                    <el-form-item label="生成数量">
                        <el-input-number v-model="generateConfig.count" :min="1" :max="1000"></el-input-number>
                    </el-form-item>
                    
                    <el-form-item>
                        <el-button type="primary" @click="generateData">生成SQL</el-button>
                    </el-form-item>
                </el-form>
                
                <!-- 生成结果 -->
                <el-input
                    v-model="generatedSQL"
                    type="textarea"
                    :rows="10"
                    placeholder="生成的SQL将显示在这里"
                ></el-input>
            </el-main>
        </el-container>
    `
}

createApp(app).use(ElementPlus).mount('#app') 